package org.yunmai.service.impl;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.yunmai.dto.LoginDto;
import org.yunmai.remote.AuthOpenFeignRemote;
import org.yunmai.service.AuthService;
import org.yunmai.util.JwtUtil;
import org.yunmai.util.KeyPairUtil;
import org.yunmai.util.R;
import org.yunmai.util.SecretBeanUtil;
import org.yunmai.vo.LoginVo;
import org.yunmai.vo.MemberVo;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 小灰灰
 */
@Service
@Primary
public class UserServiceImpl implements AuthService {

    @Autowired
    AuthOpenFeignRemote authRemote;

    private final String TOKEN_KEY = "token@123";
    @Autowired
    private SecretBeanUtil secretBeanUtil;

    @Override
    public R<String> loginAndToken(LoginDto loginDto) {
        R<LoginVo> userInfo = authRemote.login(loginDto);
        if (userInfo != null && userInfo.getCode().equals(200)) {
            LoginVo data = userInfo.getData();
            Map<String,Object> map = new HashMap<>();
            map.put("username", data.getUsername());
            map.put("rolename", data.getRolename());
            map.put("email", data.getEmail());
            map.put("phone", data.getPhone());
            map.put("address", data.getAddress());
            String token = JwtUtil.generateJWT(KeyPairUtil.getPrivateKey(secretBeanUtil.getPrivateKey()), map);
            return R.build(200, "登陆成功", token);
        }
        return R.build(500, "登陆失败", null);
    }

    @Override
    public R<MemberVo> memberInfo(String token)  {
        R<MemberVo> userInfo = authRemote.userInfo(token);
        if (userInfo != null && userInfo.getCode().equals(200)) {
            return R.build(200, "登陆成功", userInfo.getData());
        }
        return R.build(500, "登陆失败", null);
    }
}
